package com.rzico.sbl.ui.order

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderShipWhereBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.slimadapter.SlimAdapter

class OrderShipWhereActivity : BaseActivity(R.layout.activity_order_ship_where) {

    private val mBinding by lazy { ActivityOrderShipWhereBinding.bind(getRootView()) }

    private var mKeyWord = ""

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关配送站信息！"
                }

                recycleList.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) }
                )

                recycleList.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<CommonData>(R.layout.item_where_list) { jector, bean, _ ->
                        jector.text(R.id.item_where_title, bean.name)
                            .text(R.id.item_where_name, bean.linkman)
                            .text(R.id.item_where_tel, bean.telephone)
                            .text(R.id.item_where_addr, bean.address)

                            .with<ImageView>(R.id.item_where_logo) {
                                it.loadCircleImage(bean.logo, R.mipmap.default_user)
                            }

                            .with<TextView>(R.id.item_where_distance) {
                                it.text = bean.distance.formatDistance()
                                it.isGone = bean.distance.doubleValue == 0.0
                            }

                            .clicked(R.id.item_where_call) {
                                bean.telephone.notEmpty {
                                    showBottomPhoneDialog(this)
                                }
                            }

                            .clicked {
                                val fields = arrayListOf(
                                    "shop",
                                    bean.id,
                                    bean.name.orEmpty(),
                                    bean.enterpriseId,
                                    bean.xmid,
                                    bean.lat.orEmpty(),
                                    bean.lng.orEmpty()
                                )

                                LiveEventBus
                                    .get("orderShip")
                                    .post(fields.joinToString(","))

                                finishView()
                            }
                    }
                    .attachTo(recycleList)
            }
    }

    private fun initSearch() {
        mBinding
            .whereSearch
            .apply {
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入关键字")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入关键字")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    /**
     * 配送站列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .requestModel(
                isMultipart = true,
                requestUrl = BaseUrl.shopList,
                params = arrayOf(
                    "lat" to intent.getExtra("lat"),
                    "lng" to intent.getExtra("lng"),
                    "searchValue" to mKeyWord,
                    "pageStart" to index * 10,
                    "pageSize" to 10
                ),
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}